// asyncPackageComponent/audioChatType/audioChatType.js
const Base64 = require("js-base64").Base64;
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    itemDatas: {
      type: null,
    },
    open: {
      type: Boolean,
      value: false,
    },
    sendStatus:{
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    websock: null,
    wsuri: "",
    vcn: "",
    baseStr: [],
    baseStrlink: "",
    audioTxt: "",
    appid:""
  },
  lifetimes:{
    attached(){
      console.log(this.properties.itemDatas,'itemDatas')
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async tapAudit(e) {
      let {
        content
      } = e.currentTarget.dataset;
      if (content) {
        this.setData({
          audioTxt: content,
        });
      }
      this.setData({
        baseStrlink: "",
        baseStr: [],
      });
      this.triggerEvent("showLoad")
      let {
        data
      } = await app._postNetWork({
        url: app.getNetAddresss(
          "plugin.ai-digital-human.frontend.controllers.chat.get-assemble-auth-url"
        ),
      });
      if (data.result) {
        this.setData({
          wsuri: data.data.url,
          vcn: data.data.vcn,
          appid: data.data.app_id
        });
        this.data.websock = wx.connectSocket({
          url: data.data.url,
        });
        this.data.websock.onMessage((e) => {
          this.websocketonmessage(e);
        });
        this.data.websock.onOpen(() => {
          this.websocketonopen();
        });
        this.data.websock.onError((e) => {
          this.websocketonerror(e);
        });
      } else {
        app.tips(data.msg);
        this.triggerEvent("closeLoad");
      }
    },
    websocketonmessage(e) {
      let jsonData = JSON.parse(e.data);
      if (jsonData.data.audio) {
        let arr = this.data.baseStr.push(jsonData.data.audio);
        this.setData({
          baseStr: this.data.baseStr,
        });
      }
      if (jsonData.data.status === 2) {
        this.joinM();
        this.data.websock.close();
        this.triggerEvent("closeLoad");
      } else {
        this.setData({
          audioStatus: true,
        });
      }
    },
    saveArrayBufferToFile(arrayBuffer) {
      return new Promise((resolve, reject) => {
        wx.getFileSystemManager().writeFile({
          filePath: wx.env.USER_DATA_PATH + "/temp_audio.WAV",
          data: arrayBuffer,
          encoding: "binary",
          success: function (res) {
            resolve(wx.env.USER_DATA_PATH + "/temp_audio.WAV");
          },
          fail: function (err) {
            reject(err);
          },
        });
      });
    },
    async joinM() {
      try {
        let arrayBuffer = this.concatBuffer();
        arrayBuffer = wx.base64ToArrayBuffer(arrayBuffer);
        // 保存 ArrayBuffer 到临时文件
        const filePath = await this.saveArrayBufferToFile(arrayBuffer);
        if (filePath) {
          this.setData({
            baseStrlink: filePath,
          });
          // 播放音频
          // this.playAudio(filePath);
          this.triggerEvent('childAudio', filePath)
        } else {
          console.log("音频链接无效");
        }
      } catch (error) {
        app.tips(error);
        console.error("处理音频时出错:", error);
      }
    },
    concatBuffer() {
      // 检查 base64 字符串数组是否存在
      if (!Array.isArray(this.data.baseStr) || this.data.baseStr.length === 0) {
        console.log("baseStr must be a non-empty array of base64 strings.");
        return null;
      }

      // 将每个 base64 字符串转换为 ArrayBuffer
      const arrayBuffers = this.data.baseStr.map((base64Str) => {
        try {
          return wx.base64ToArrayBuffer(base64Str);
        } catch (error) {
          console.error("Invalid base64 string:", base64Str, error);
          return null;
        }
      });

      // 过滤掉无效的 ArrayBuffer
      const validArrayBuffers = arrayBuffers.filter(
        (arrayBuffer) => arrayBuffer !== null
      );
      console.log(validArrayBuffers);
      // 如果没有有效的 ArrayBuffer，返回错误
      if (validArrayBuffers.length === 0) {
        console.error("No valid base64 strings found.");
        return null;
      }

      // 合并所有有效的 ArrayBuffer
      const totalLength = validArrayBuffers.reduce(
        (acc, arrayBuffer) => acc + arrayBuffer.byteLength,
        0
      );
      const combinedArrayBuffer = new ArrayBuffer(totalLength);
      const combinedUint8Array = new Uint8Array(combinedArrayBuffer);
      let offset = 0;
      validArrayBuffers.forEach((arrayBuffer) => {
        combinedUint8Array.set(new Uint8Array(arrayBuffer), offset);
        offset += arrayBuffer.byteLength;
      });

      // 将合并后的 ArrayBuffer 转换回 base64 字符串
      const combinedBase64 = wx.arrayBufferToBase64(combinedArrayBuffer);

      return combinedBase64;
    },
    playAudio(filePath) {
      const innerAudioContext = wx.createInnerAudioContext({
        useWebAudioImplement: false,
      });
      this.data.innerAudioCtx = innerAudioContext;
      innerAudioContext.src = filePath;
      innerAudioContext.play();
      innerAudioContext.onPlay(() => {
        this.setData({
          isPlaying: true,
        });
      });
      innerAudioContext.onEnded(() => {
        this.setData({
          audioStatus: false,
          isPlaying: false,
        });
      });
      innerAudioContext.onError((res) => {
        this.setData({
          audioStatus: false,
          isPlaying: false,
        });
        console.error("播放音频时出错:", res.errMsg, res.errCode);
      });
    },
    websocketonopen() {
      let params = {
        common: {
          app_id: this.data.appid,
        },
        business: {
          aue: "lame",
          sfl: 1,
          auf: "audio/L16;rate=16000",
          vcn: this.data.vcn,
          speed: 50,
          volume: 50,
          pitch: 50,
          bgs: 1,
          tte: "UTF8",
        },
        data: {
          status: 2,
          text: Base64.encode(this.data.audioTxt),
        },
      };
      this.data.websock.send({
        data: JSON.stringify(params),
      });
    },
    websocketonerror(e) {
      console.log(e, "::::::error");
      this.triggerEvent("closeLoad");
    },
  },
});